<template>
  <c-loading :loading="loading">
    <view class="login-container pad flex-center al-center">
      <view>
        <view class="login-banner">
          <c-img class="img" mode="aspectFit" :src="state.info.logo" />
          <text class="names">{{ state.info.name }}</text>
        </view>
        <view class="btn-box">
          <c-button v-if="!state.agree" @tap="onTips" type="primary">一键授权手机号</c-button>
          <c-button v-else type="primary" open-type="getPhoneNumber" :loading="state.disabled" @getphonenumber="getPhonenumber">一键授权手机号</c-button>
          <view class="agree" :class="{ shake: state.shake }">
            <c-checkbox class="check" :checked="state.agree" @tap="state.agree = !state.agree">我已阅读并同意</c-checkbox>
            <text class="link" @tap="router.push('/pagesBus/article/helpInfo?code=protocol')">《平台服务协议》</text>
          </view>
        </view>
      </view>
    </view>
  </c-loading>
</template>
<script setup>
import { userBindMobile } from '@/api/user';
import { CImg, CLoading, CButton, CCheckbox } from '@/components';
import { View, Text } from '@tarojs/components';
import { cache } from '@/utils';
import { reactive, ref } from 'vue';
import { afterLogin, useLoading, useRouter } from '@/hooks';
import api from '@/api';

const router = useRouter();

const state = reactive({
  info: {},
  loading: false,
  agree: false,
  shake: false,
  disabled: false
});

const getPhonenumber = async e => {
  if (e.detail.errMsg == 'getPhoneNumber:ok') {
    state.disabled = true;
    const token = await userBindMobile({
      code: e.detail.code
    })
      .finally(() => {
        state.disabled = false;
      })
      .error();
    cache.set('token', token, 3600 * 24 * 7);
    await doInvite();
    router.back(true);
  }
};
const doInvite = () => {
  var inviteId = cache.get('InviteId');
  if (inviteId) {
    return api.user.userBindInvite(inviteId);
  }
};
const onTips = e => {
  state.shake = true;
  setTimeout(() => {
    state.shake = false;
  }, 1000);
};

const { loading } = useLoading(async () => {
  await afterLogin();
  state.info = await api.user.appCurretApp();
});
</script>
<style lang="scss">
.login-container {
  height: 100vh;
  padding-bottom: max(20px, var(--safe-bottom));
  .login-banner {
    margin: auto;
    text-align: center;
    font-weight: bold;
    font-size: 30px;
    padding-bottom: 180px;
    .img {
      width: 200px;
      height: 200px;
      margin: 0 auto 50px;
      border-radius: 10px;
      box-shadow: 0 0 20px rgba(0, 0, 0, 0.3);
    }
  }

  .btn-box {
    width: 100vw;
    position: absolute;
    left: 0;
    padding: 0 30px 10px;
    box-sizing: border-box;
    bottom: var(--safe-bottom);
  }
  .agree {
    text-align: center;
    line-height: 30px;
    margin: 50px 0 30px;
    font-size: 26px;
    display: flex;
    align-items: center;
    justify-content: center;

    .link {
      display: inline-block;
      color: var(--color-primary);
    }
  }
}
</style>
